package com.collegeproject.weatherapp.fragments;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.collegeproject.weatherapp.R;
import com.collegeproject.weatherapp.StartActivity.AppSectionsPagerAdapter;
import com.collegeproject.weatherapp.StartActivity.FragmentListener;
import com.collegeproject.weatherapp.library.AsyncResponse;
import com.collegeproject.weatherapp.library.ConnectionDetector;
import com.collegeproject.weatherapp.library.DatabaseHandler;
import com.collegeproject.weatherapp.library.HTTPfunctions;

public class LoginFragment extends Fragment implements AsyncResponse {

	EditText inputUserName, inputPass;
	Button loginButton, registerButton, recoveryButton;
	TextView loginError, login_url;
	HTTPfunctions task;
	JSONObject jsonObject;
	static FragmentListener _listener;
	ConnectionDetector cd;

	// private static final String KEY_ID = "id";
	private static final String KEY_USERNAME = "UserName";
	private static final String KEY_USERID = "UserId";
	private static final String KEY_FIRSTNAME = "FirstName";
	private static final String KEY_LASTNAME = "LastName";
	private static final String KEY_EMAIL = "Email";

	private String mPassword, mUserName;

	private static final String TAG = "LoginFragment"; // for log
	
	private static final String GETAUTH = "GETAUTH";
	// private static String localLoginURL = "http://10.0.2.2:8080/WeatherAppService.svc/rest/login";
	private static String loginURL = "http://x00068868.cloudapp.net/WeatherAppService/rest/login";

	public static LoginFragment newInstance(
			FragmentListener loginFragmentListener) {
		LoginFragment f = new LoginFragment();
		_listener = loginFragmentListener;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.login, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		cd = new ConnectionDetector(getActivity());
	}

	@Override
	public void onStart() {
		super.onStart();
		
		inputPass.setOnEditorActionListener(new OnEditorActionListener() {
			
			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				// search button pressed
				if (actionId == EditorInfo.IME_ACTION_SEND) {

					mUserName = inputUserName.getText().toString().trim();
					mPassword = inputPass.getText().toString().trim();

					attemptLogin(mUserName, mPassword);

					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					
					return true;
				}
				return false;
			}
		});
		
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUserName = inputUserName.getText().toString().trim();
				mPassword = inputPass.getText().toString().trim();

				attemptLogin(mUserName, mPassword);
			}
		});

		registerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				AppSectionsPagerAdapter.FragmentToChangeTo = 5; // switch to
																// RegisterFragment
				_listener.onSwitchToNextFragment(); // fragment listener call
			}
		});

		recoveryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				AppSectionsPagerAdapter.FragmentToChangeTo = 6; // switch to
																// PassRecoveryFragment
				_listener.onSwitchToNextFragment(); // fragment listener call
			}
		});
	}

	private void attemptLogin(String username, String pass) {
		// Reset errors.
		inputUserName.setError(null);
		inputPass.setError(null);

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			inputPass.setError(getString(R.string.error_field_required));
			focusView = inputPass;
			cancel = true;
		} else if (mPassword.length() < 6) {
			inputPass.setError(getString(R.string.error_field_lesschar));
			focusView = inputPass;
			cancel = true;
		}

		// Check for a valid user name.
		if (TextUtils.isEmpty(mUserName)) {
			inputUserName.setError(getString(R.string.error_field_required));
			focusView = inputUserName;
			cancel = true;
		}
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			try {
				Boolean connected = cd.isConnectingToInternet();
				if (connected){
					loginError.setVisibility(View.GONE);

					String source = mUserName + ":" + mPassword;
					String base64 = Base64.encodeToString(
							source.getBytes("UTF-8"), Base64.URL_SAFE
									| Base64.NO_WRAP);

					task = new HTTPfunctions(getActivity(), GETAUTH, base64);
					task.listener = this;
					task.execute(new String[] { loginURL });
				} else {
					loginError.setText("No internet connection available");
					loginError.setVisibility(View.VISIBLE);
				}
			} catch (Exception ex) {
				Log.e(TAG + " Attempted Login ", ex.getMessage());
			}
		}

	}

	@Override
	public void processFinish(String result) { // get result from HTTFuction
												// AsynClass
		try {
			jsonObject = new JSONObject(result);
			int success = Integer.parseInt(jsonObject.getString("Success"));
			if (success == 0) {
				JSONObject user = jsonObject.getJSONObject("User");

				DatabaseHandler db = new DatabaseHandler(getActivity());
				// add return user details to table
				db.resetTables();
				db.addUser(user.getString(KEY_USERNAME),
						user.getString(KEY_EMAIL), user.getString(KEY_USERID),
						user.getString(KEY_FIRSTNAME),
						user.getString(KEY_LASTNAME), mPassword);

				AppSectionsPagerAdapter.FragmentToChangeTo = 1;
				_listener.onSwitchToNextFragment(); // switch to
													// DashboardFragment
			} else {
				loginError.setText(jsonObject.getString("ErrorMessage"));
				loginError.setVisibility(View.VISIBLE);
			}
		} catch (JSONException e) {
			Log.e(TAG, "JSON parsing from login result " + e.getMessage());
		}
	}

	private void initViews() {
		inputUserName = (EditText) getView().findViewById(
				R.id.edit_login_username);
		inputPass = (EditText) getView().findViewById(R.id.edit_login_pass);
		loginButton = (Button) getView().findViewById(R.id.button_login);
		registerButton = (Button) getView().findViewById(
				R.id.button_LinkToRegisterScreen);
		recoveryButton = (Button) getView()
				.findViewById(R.id.button_forgotPass);

		loginError = (TextView) getView().findViewById(R.id.login_error);
		login_url = (TextView) getView().findViewById(R.id.login_url);

	}
}
